package com.hyh.eblog.config;

import cn.hutool.core.map.MapUtil;
import com.hyh.eblog.shiro.AccountRealm;
import com.hyh.eblog.shiro.AuthFilter;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author Summerday
 */
@Slf4j
@Configuration
public class ShiroConfig {

    //private static final Logger log = LoggerFactory.getLogger(ShiroConfig.class);

    @Bean
    public DefaultWebSecurityManager securityManager(AccountRealm realm) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(realm);
        log.info("--------------> security Manager <--------------");
        return securityManager;
    }

    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(DefaultWebSecurityManager securityManager) {
        ShiroFilterFactoryBean filterFactoryBean = new ShiroFilterFactoryBean();
        filterFactoryBean.setSecurityManager(securityManager);

        filterFactoryBean.setLoginUrl("/user/login");
        filterFactoryBean.setSuccessUrl("/user/center");

        filterFactoryBean.setUnauthorizedUrl("/error/403");
        filterFactoryBean.setFilters(MapUtil.of("auth", authFilter()));
        Map<String, String> map = new LinkedHashMap<>();
        map.put("/user/login", "anon");

        map.put("/user/home", "authc");
        map.put("/user/set", "authc");
        map.put("/user/message", "authc");
        map.put("/user/index", "authc");
        map.put("/user/upload", "authc");

        map.put("/collection/remove", "authc");
        map.put("/collection/find", "authc");
        map.put("/collection/add", "authc");

        map.put("/post/edit","authc");

        filterFactoryBean.setFilterChainDefinitionMap(map);
        return filterFactoryBean;
    }

    @Bean
    public AuthFilter authFilter() {
        return new AuthFilter();
    }
}
